package com.geek.nio3work.nio2.router;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: lishuangqiang
 * @Date: 2021/11/21
 * @Description:
 */

public class WeightRandomHttpEndpointRouter implements HttpEndpointRouter {
    @Override
    public String route(List<String> endpoints) {
        Map<String, Integer> endpointsMap = new HashMap();
        List<String> filterList = new ArrayList();
        for (int i = 0; i < endpoints.size(); i++) {
            endpointsMap.put(endpoints.get(i), i + 1);
        }
        for (String endpoint : endpoints) {
            int weight = endpointsMap.get(endpoint);
            for (int i = 0; i < weight; i++) {
                filterList.add(endpoint);
            }
        }
        Random random = ThreadLocalRandom.current();
        int pos = random.nextInt(filterList.size());
        return filterList.get(pos);
    }
}
